<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Title</title>
    <script src="static/js/jquery.min.js" type="text/javascript"></script>
    <link href="static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <script src="static/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
</head>
<body>
<%--搭建显示页面--%>
<div class="jumbotron text-center" style="margin-bottom:0">
    <h1>员工信息管理表</h1>
</div>
<div class="container">
    <%--删除按钮--%>
    <div class="row">
        <div class="col-md-4"><h4>员工基本信息</h4></div>
        <div class="col-md-4 col-md-offset-4">
            <button class="btn btn-primary" data-toggle="modal" id="emp_add_btn">新增</button>
            <button class="btn btn-danger">删除</button>
        </div>
    </div>
    <%--表格数据--%>
    <div class="row">
        <div class="col-lg-12">
            <table class="table table-striped">

                <thead>
                <tr>
                    <th>ID</th>
                    <th>Lastname</th>
                    <th>email</th>
                    <th>gender</th>
                    <th>deptName</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
    <%--分页--%>
    <div class="row">
        <div class="col-md-6" id="pageInfo">

        </div>
        <div class="col-md-6">
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <%--                    <c:if test="${pageInfo.isFirstPage}">
                                            <li class="disabled"><a href="#">首页</a></li>
                                        </c:if>

                                        <c:if test="${!pageInfo.isFirstPage}">
                                            <li><a href="${APP_PATH}/emps">首页</a></li>
                                        </c:if>
                                        <c:if test="${pageInfo.hasPreviousPage}">
                                            <li>
                                                <a href="${APP_PATH}/emps?pn=${pageInfo.prePage}" aria-label="Previous">
                                                    <span aria-hidden="true">&laquo;</span>
                                                </a>
                                            </li>
                                        </c:if>
                                        <c:if test="${!pageInfo.hasPreviousPage}">
                                            <li class="disabled">
                                                <a href="#" aria-label="Previous">
                                                    <span aria-hidden="true">&laquo;</span>
                                                </a>
                                            </li>
                                        </c:if>
                                        <c:forEach items="${pageInfo.navigatepageNums}" var="num">
                                            <c:if test="${pageInfo.pageNum==num}">
                                                <li class="active"><a href="#">${num}</a></li>
                                            </c:if>
                                            <c:if test="${pageInfo.pageNum!=num}">
                                                <li><a href="${APP_PATH}/emps?pn=${num}">${num}</a></li>
                                            </c:if>

                                        </c:forEach>
                                        <c:if test="${!pageInfo.hasNextPage}">
                                            <li class="disabled">
                                                <a href="#" aria-label="Next">
                                                    <span aria-hidden="true">&raquo;</span>
                                                </a>
                                            </li>
                                        </c:if>
                                        <c:if test="${pageInfo.hasNextPage}">
                                            <li>
                                                <a href="${APP_PATH}/emps?pn=${pageInfo.nextPage}" aria-label="Next">
                                                    <span aria-hidden="true">&raquo;</span>
                                                </a>
                                            </li>
                                        </c:if>

                                        <c:if test="${pageInfo.isLastPage}">
                                            <li class="disabled"><a href="#">末页</a></li>
                                        </c:if>
                                        <c:if test="${!pageInfo.isLastPage}">
                                            <li><a href="${APP_PATH}/emps?pn=${pageInfo.pages}">末页</a></li>
                                        </c:if>--%>
                </ul>
            </nav>
        </div>

    </div>
</div>
<%--员工添加模态框--%>
<div class="modal fade" id="emp_edit_modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empName" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" name="empName" class="form-control" id="empName" placeholder="empName">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="email"
                                   placeholder="email@sun.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">department</label>
                        <div class="col-sm-4">
                            <%--提交部门id--%>
                            <label>
                                <select class="form-control depts" name="dId"></select>
                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script type="text/javascript">
    let totalRecord;
    $(function () {
        to_page(1);
    });

    function to_page(pn) {
        $.ajax({
            url: "${APP_PATH}/emps",
            data: "pn=" + pn,
            type: "Get",
            success: function (res) {
                console.log(res);
                //1. 解析并显示员工数据
                build_emps_table(res);
                //2. 解析并显示分页信息
                build_page_info(res);
                //3. 解析显示分页条数据
                build_page_nav(res);
            }
        })
    }

    function build_emps_table(res) {
        const emps = res.extend.pageInfo.list;
        $("tbody").empty();
        $.each(emps, function (index, item) {
            const empId = $("<td></td>").append(item.empId);
            const empName = $("<td></td>").append(item.empName);
            const email = $("<td></td>").append(item.email);
            const gender = $("<td></td>").append(item.gender === "M" ? "男" : "女");
            const department = $("<td></td>").append(item.department.deptName);
            const btn = $("<td>\n" +
                "                            <button class=\"btn btn-primary btn-sm\">\n" +
                "                        <span class=\"glyphicon glyphicon-pencil\">\n" +
                "                            编辑\n" +
                "                        </span>\n" +
                "                            </button>\n" +
                "                            <button class=\"btn btn-danger btn-sm\">\n" +
                "                        <span class=\"glyphicon glyphicon-remove\">\n" +
                "                            删除\n" +
                "                        </span>\n" +
                "                            </button>\n" +
                "                        </td>");
            const tr = $("<tr></tr>").append(empId).append(empName).append(gender).append(email).append(department).append(btn);
            $("tbody").append(tr);
            //console.log(item.empName)
        })
    }

    function build_page_info(res) {
        const infoEle = $("#pageInfo");
        infoEle.empty();
        const pageNum = res.extend.pageInfo.pageNum;
        const pages = res.extend.pageInfo.pages;
        const total = res.extend.pageInfo.total;
        infoEle.append("当前第" + pageNum + "页 总" + pages + "页 共" + total + "条录数");
        totalRecord = total;
    }

    function build_page_nav(res) {

        const pageInfo = res.extend.pageInfo;
        const ul = $("ul.pagination");
        ul.empty();
        const firstli = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#"));
        const lastli = $("<li></li>").append($("<a></a>").append("末页").attr("href", "#"));
        const preli = $("<li></li>").append($("<a></a>").append("<span>&laquo;</span>"));
        const nextli = $("<li></li>").append($("<a></a>").append("<span>&raquo;</span>"));
        if (pageInfo.isFirstPage) {
            firstli.addClass("disabled");
            preli.addClass("disabled");
        } else {
            firstli.click(function () {
                to_page(1);
            });
            preli.click(function () {
                to_page(pageInfo.prePage)
            });
        }

        if (pageInfo.isLastPage) {
            lastli.addClass("disabled");
            nextli.addClass("disabled");
        } else {
            nextli.click(function () {
                to_page(pageInfo.nextPage);
            });
            lastli.click(function () {
                to_page(pageInfo.pages);
            });
        }

        ul.append(firstli).append(preli);
        $.each(pageInfo.navigatepageNums, function (index, num) {
            //console.log(num);
            let pageli = $("<li></li>").append($("<a></a>").append(num));
            pageli.click(function () {
                to_page(num);
            });
            if (pageInfo.pageNum === num) {
                pageli.addClass("active")
            }

            ul.append(pageli);
        });
        ul.append(nextli).append(lastli);
    }


    $("#emp_add_btn").click(function () {
        //清除表单信息
        reset_form("#emp_edit_modal form");

        //发送ajax信息，查询部门信息
        getDepts();
        //弹出模态框
        $("#emp_edit_modal").modal({
            backdrop: "static",
            keyboard: false
        });
    });

    //获取员工信息
    function getDepts() {
        $.ajax({
            url: "${APP_PATH}/depts",
            type: "get",
            success: function (res) {
                $("select.depts").empty();
                $.each(res.extend.depts, function (index, item) {
                    const optionEle = $("<option value=" + item.deptId + "></option>").append(item.deptName);
                    $("select.depts").append(optionEle);
                })
            }
        });
    }


    //展示提示信息
    function show_validate_msg(ele, status, msg) {
        //清除元素当前状态
        ele.parent().removeClass("has-error has-success");
        ele.next("span").text("");
        if ("success" === status) {
            ele.parent().addClass("has-"+status);
            ele.next("span").text(msg);
        }else if ("error" === status) {
            ele.parent().addClass("has-"+status);
            ele.next("span").text(msg);
        }

    }

    //添加员工信息表单校验
    function validate_add_form() {
        //1. 拿到校验数据,使用正则表达式
        const empNameInput = $("#empName");
        // 判断用户名重复校验是否成功
        if(empNameInput.attr("isChecked")!=="success"){
            return false;
        }
        const regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
        if(!regName.test(empNameInput.val())){
            //alert("用户名为2-5位的中文字符或6-16位的英文数字组合");
            show_validate_msg(empNameInput,"error","用户名为2-5位的中文字符或6-16位的英文数字组合");
            return false;
        }else {
            show_validate_msg(empNameInput,"success","用户名正确");
        }

        //2. 校验邮箱信息
        const emailInput = $("#email");
        const regEmail=new RegExp(/\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/);
        if(!regEmail.test(emailInput.val())){
            //alert("邮箱格式错误");
            show_validate_msg(emailInput,"error","邮箱格式错误");
            return false;
        }else{
            show_validate_msg(emailInput,"success","");
        }
        return true;
    }


    //检查用户名是否可用
    $("#empName").change(function () {
        //发送校验请求，查看是否重复
        $.ajax({
            url: "${APP_PATH}/checkUser",
            data: "empName=" + this.value,
            type: "get",
            success:function (res) {
                const empNameInput = $("#empName");
                if(res.code===100){
                    show_validate_msg(empNameInput,"success","用户名可用");
                    empNameInput.attr("isChecked", "success");
                }else {
                    show_validate_msg($("#empName"),"error",res.extend.va_msg);
                    empNameInput.attr("isChecked", "error");
                }
            }
        })
    });

    //清空表单样式
    function reset_form(ele){
        //清空表单内容
        $(ele)[0].reset();
        //清空样式
        $(ele).find("*").removeClass("has-error has-success");
        //移除辅助标识
        $(ele).find(".help-block").text("")
    }
    //保存表单信息
    $("#emp_save_btn").click(function () {
        //1. 对表单数据进行校验
        if (!validate_add_form()) {
            return false;
        }

        //2. 发送保存请求
        $.ajax({
            url: "${APP_PATH}/emp",
            type: "post",
            data: $("#emp_edit_modal form").serialize(),
            success: function (res) {

                if(res.code==100){
                    //保存成功
                    //关闭模态框
                    $("#emp_edit_modal").modal("hide");
                    //跳转最后一页
                    to_page(totalRecord);
                    alert(res.msg);
                }else{
                    //显示字段的错误信息
                    //console.log(res);
                    if(!res.extend.errorFileds.email){
                        //显示邮箱错误信息
                        alert(res.extend.errorFileds.email);
                    }
                    if(!res.extend.errorFileds.empName){
                        //显示员工姓名的错误信息
                        alert(res.extend.errorFileds.empName);
                    }
                }
            }
        });
    })
</script>
</body>
</html>